//
//  LoginAPI.swift
//  QingLiuSwift
//
//  Created by xyanl on 2023/8/9.
//

import Foundation
import JKSwiftExtension
import Moya
import SwiftyUserDefaults
import Localize_Swift

// RequestAPI就是一个遵循TargetType协议的枚举
enum LoginAPI {
    // 正式
    // MARK: 登录
    
    /// 账号登录
    /// - Parameters:
    ///   - country: 国家编号，0：中国，1：俄罗斯
    ///   - account: 手机号
    ///   - password: 手机号
    case loginAccount(country: Int, account: String?, password: String?)
    
    /// 验证码登录
    /// - Parameters:
    ///   - captcha: 验证码
    ///   - mobile: 手机号
    ///   - country: 国家 id
    case loginCode(captcha: String, mobile: String, country: Int)
    
    /// 获取验证码
    /// - Parameters:
    ///   - areaCode: 区号
    ///   - mobile: 手机号
    ///   - event: 注册：register，手机号登录：mobilelogin，重置密码：resetpwd，
    ///   俄语注册：register_ru，俄语重置密码：resetpwd_ru
    ///   - email: 俄语时 随便传个邮箱
    case getSMS(areaCode: String, mobile: String, event: String, email: String?)
    
    /// 重置密码
    /// - Parameters:
    ///   - captcha: 验证码
    ///   - mobile: 手机号
    ///   - password: 密码
    ///   - country: 国家 id
    case resetPassword(captcha: String, mobile: String, password: String, country: Int)
    
    /// 注册账号
    /// - Parameters:
    ///   - mobile: 手机号
    ///   - captcha: 验证码
    ///   - password: 密码
    ///   - country: 国家 0中国 1俄罗斯
    ///   - name: 用户名称、公司名
    ///   - avatar: 头像, 头像可以不传,默认空字符串
    ///   - identityId: 身份 id
    ///   - cityId: 城市 id
    ///   - inviterCode: 邀请码
    case register(mobile: String, captcha: String, password: String, country: Int, name: String, avatar: String, identityId: Int, cityId: Int, inviterCode: String?, email: String?)
    /// 地址选择器
    /// - Parameters:
    ///   - country: 0：中国，1：其他国家
    ///   - pid: 好像没啥用
    ///   - isPort: true：中国+其他国家，false：只有中国
    case cityList(country: Int, pid: Int, isPort: Bool)
    
    /// 用户信息
    /// - Parameters:
    ///   - id: 用户 id
    case userInfo(_ id: String)
    
    /// 个人主页 用户信息
    case user(_ id: String)
    
    /// 客服电话列表
    case customerMobiles
    
    /// GLUZ用户账号服务协议
    case serviceAgreement(type: String, language: String, version: String)
    
    /// 强制更新
    case systemForcedUpdating
    
    // 占位
    case placeholderApi
}

extension LoginAPI: TargetType {
    // 请求地址
    var baseURL: URL {
        return URL(string: SystemEnvManager.shared.phpUrl)!
    }
    
    // 请求API
    var path: String {
        switch self {
        case .loginAccount: return "/api/user/login"
        case .loginCode: return "/api/user/mobilelogin"
        case .getSMS: return "/api/sms/send"
        case .resetPassword: return "/api/user/resetpwd"
        case .cityList: return "/api/basic/getSelectCityList"
        case .register: return "/api/user/newRegister"
        case .userInfo: return "/api/notoken/getIdentity"
        case .user: return "/api/user/getUserHomepage"
        case .customerMobiles: return "/api/userAudit/customer_tel"
        case .serviceAgreement: return "/api/basic/getContentData"
        case .systemForcedUpdating: return "/api/Notoken/getVersion"
            
        default:
            fatalError("Request path is null")
        }
    }
    // 请求方式: post/get
    var method: Moya.Method {
        switch self {
        case .placeholderApi, .cityList, .userInfo, .serviceAgreement, .customerMobiles:
            return .get
        default: // 默认post请求
            return .post
        }
    }
    
    // 请求任务
    var task: Moya.Task {
        // 公共参数
        var params: [String: Any] = [:]
        // params["token"] = "a1c965c2-2308-4de6-bb10-354ae8845a6e"
        // params["client"] = "app"
        
        // 根据不同的接口传入不同的参数
        switch self {
            
        case .loginAccount(let country, let account, let password):
            params["country"] = country // 国家编号
            params["account"] = account // 账号
            params["password"] = password // 密码
            
        case .loginCode(let captcha, let mobile, let country):
            params["captcha"] = captcha
            params["mobile"] = mobile
            params["event"] = country == 0 ? "mobilelogin": "mobilelogin_ru"
            params["country"] = country
            
        case .getSMS(let areaCode, let mobile, let event, let email):
            // 注册：register，手机号登录：mobilelogin，重置密码：resetpwd，
            // 俄语注册：register_ru，手机号登录：mobilelogin_ru，俄语重置密码：resetpwd_ru
            params["area_code"] = areaCode
            params["event"] = event
            params["mobile"] = mobile
            params["lang"] = "zh"
            params["langs"] = "zh"
            params["version"] = 1.0  // 版本控制
        
            if areaCode != "86" {
                params["event"] = event + "_ru"
                params["email"] = email
                params["lang"] = "ru"
                params["langs"] = "ru"
            }
            
        case .resetPassword(let captcha, let mobile, let password, let country):
            params["captcha"] = captcha
            params["mobile"] = mobile
            params["newpassword"] = password
            params["country"] = country
            params["type"] = "mobile"
            
        case .cityList(let country, let pid, let isPort):
            params["country"] = country
            params["pid"] = pid
            params["lang"] = country == 0 ? "zh": "ru"
            params["is_port"] = String(isPort ? 1: 0)
            params["version"] = "2.3.8" // 版本号
            
        case .register(let mobile, let captcha, let password, let country, let name, let avatar, let identityId, let cityId, let inviterCode, let email):
            params["mobile"] = mobile
            params["captcha"] = captcha
            params["password"] = password
            params["country"] = country
            params["lang"] = country == 0 ? "zh": "ru"
            
            params["name"] = name
            params["avatar"] = avatar
            params["identity_id"] = identityId
            params["area_new_id"] = cityId
            params["identity_set_type"] = 1
            params["agent_code"] = inviterCode
            params["email"] = email
            params["version"] = 1.0  // 版本控制
            
            
        case .userInfo(let id):
            params["uid"] = id
            
        case .user(let id):
            params["user_id"] = id
            
        case .serviceAgreement(let type, let language, let version):
            params["type"] = type
            params["lang"] = language
            params["nowlang"] = language
            params["version"] = version
            
        case .systemForcedUpdating:
            params["type"] = "IOS"
            
        default:
            break
        }
        
        // 设置请求类型, 比如没有参数的请求、有参数的请求、上传文件、下载文件
        switch self {
        case .placeholderApi, .customerMobiles:
            // 没有请求参数的请求。
            return .requestPlain
            
        default:
            // 默认有请求参数
            if method == .get {
                // 在发起GET请求时，确保使用 URLEncoding.default 编码方式，这样参数会被正确添加到URL的查询字符串中，而不是作为请求体发送。
                return .requestParameters(parameters: params, encoding: URLEncoding.default)
            }
            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
        }
    }
    
    // 公共头部信息
    var headers: [String: String]? {
        var headers: [String: String] = [:]
        headers["token"] = Defaults[\.token]
        headers["client"] = "app"
        headers["Content-type"] = "application/json;charset=utf-8"
        headers["requestStartTime"] = String(CFAbsoluteTimeGetCurrent())
        return headers
    }
    
    // 通过statuscode过滤返回内容
    public var validationType: ValidationType {
        switch self {
        case .placeholderApi:
            return .successCodes
        default:
            return .none
        }
    }
    
    // 多用于单元测试,这个属性是返回Stub数据的。
    public var sampleData: Data {
        switch self {
            //        case .userInfo:
            //            return "Half measures are as bad as nothing at all.".data(using: .utf8)!
            //        case .userProfile(let name):
            //            return "{\"login\": \"\(name)\", \"id\": 100}".data(using: .utf8)!
        default:
            return "".data(using: .utf8)!
        }
    }
}
